var app = getApp();
Page({
  data: {
    packageInfo: {},
    totalPrice: 0,
    selectedItems: [],
    // 表单数据
    name: '',
    phone: '',
    idCard: '',
    selectedDate: '',
    selectedTime: '',
    remark: '',
    agree: false,
    canSubmit: false,
    // 日期选择器
    showDatePicker: false,
    dateList: [],
    dateValue: [0],
    // 时段选择器
    showTimePicker: false,
    timeList: ['08:00-09:30', '09:30-11:00', '13:30-15:00', '15:00-16:30'],
    timeValue: [0]
  },

  onLoad(options) {
    const { packageId, selectedItems, price } = options;
    this.setData({
      selectedItems: selectedItems.split(','),
	  packageId:packageId,
      totalPrice: price
    });
    this.loadPackageInfo(packageId);
    this.generateDateList();
  },

  // 加载套餐基本信息
  loadPackageInfo(packageId) {
	const packageInfo = wx.getStorageSync('packageInfo')
    this.setData({ packageInfo });
  },

  // 生成未来30天日期
  generateDateList() {
    const dateList = [];
    const today = new Date();
    for (let i = 1; i < 31; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      const month = date.getMonth() + 1;
      const day = date.getDate();
	  const year = date.getFullYear();
      const week = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];
      dateList.push(`${year}-${month}-${day}`);
    }
    this.setData({ dateList });
  },

  // 表单输入处理
  onNameChange(e) {
    this.setData({ name: e.detail.value });
    this.checkSubmitable();
  },

  onPhoneChange(e) {
    this.setData({ phone: e.detail.value });
    this.checkSubmitable();
  },

  onIdCardChange(e) {
    this.setData({ idCard: e.detail.value });
    this.checkSubmitable();
  },

  onRemarkChange(e) {
    this.setData({ remark: e.detail.value });
  },

  // 日期选择
  openDatePicker() {
    this.setData({ showDatePicker: true });
  },

  closeDatePicker() {
    this.setData({ showDatePicker: false });
  },

  onDateChange(e) {
    const index = e.currentTarget.dataset.value[0];
	console.log(index);
    this.setData({
      selectedDate: this.data.dateList[index],
      showDatePicker: false
    });
    this.checkSubmitable();
  },

  // 时段选择
  openTimePicker() {
    this.setData({ showTimePicker: true });
  },

  closeTimePicker() {
    this.setData({ showTimePicker: false });
  },

  onTimeChange(e) {    
      const index = e.currentTarget.dataset.value[0];
    this.setData({
      selectedTime: this.data.timeList[index],
      showTimePicker: false
    });
    this.checkSubmitable();
  },

  // 同意协议
  onAgreeChange(e) {
	const newAgree = !this.data.agree;
	this.setData({ agree: newAgree });
    this.checkSubmitable();
  },

  // 检查是否可以提交
  checkSubmitable() {
    const { name, phone, idCard, selectedDate, selectedTime, agree } = this.data;
    const isPhoneValid = /^1[3-9]\d{9}$/.test(phone);
    const isIdValid = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(idCard);
    const canSubmit = name && isPhoneValid && isIdValid && selectedDate && selectedTime && agree;
    this.setData({ 
		canSubmit
	});
  },

  // 打开协议
  openAgreement() {
    wx.navigateTo({ url: '/vp_pz/pages/index/html?cmd=page&id=4' });
  },

  // 提交预约
  submitAppointment() {
	  let self = this;
    if (!this.data.canSubmit) return;
	let tempId=['DOBvMP_u1QabSRLSp-oPfqyCF1afM6Wfb3xuNUBYWuQ','0Q-gDuR7DYhFuKV_k4l8YqUQ-foAnlFOB9CnIS7peiQ','tF3JZheCj1qEyZq5rwHr81CvuJQOd_yiL6Lbuj_qV2Q'];
	wx.requestSubscribeMessage({
	  tmplIds: tempId,
	  success (res) {
		if (res[tempId] === 'accept') {
		  console.log('用户同意了')  
	  
		}else if(res[tempId] == 'reject') { // 用户拒绝授权
		  wx.showModal({
			title: '温馨提示',
			content: "您已关闭消息推送，如需要消息推送服务，请点击确定跳转设置页面打开授权后再次尝试。",
			success: function(modal) {
				if (modal.confirm) { // 点击确定
					wx.openSetting({ withSubscriptions: true })
				}
			}
		})
		}
	   },
	   fail(err) { 
		 console.log(err)
		 if (err.errCode == '20004') {
		  wx.showModal({
			  title: '温馨提示',
			  content: "您的消息订阅主已关闭，如需复习提醒服务，请点击确定跳转设置页面打开授权后再次尝试。",
			  success: function(modal) {
				  if (modal.confirm) { // 点击确定
					  wx.openSetting({ withSubscriptions: true })
				  }
			  }
		  })
	  }
		},
		complete(s) {
		  wx.showLoading({ title: '提交中...' });
		  
		  try {
		    // 序列化提交数据对象
		    var form = {
		  	  name:self.data.name,
		  	  phone:self.data.phone,
		  	  idCard:self.data.idCard,
		  	  selectedDate:self.data.selectedDate,
		  	  selectedTime:self.data.selectedTime,
		  	  remark:self.data.remark
		    }
		    console.log("selectedItems:",self.data.selectedItems)
		    app.util.request({
		            url: 'Order/appointment',
		            data: {
		                form: encodeURI(JSON.stringify(form)),
		  			  selectedItems:encodeURI(JSON.stringify(self.data.selectedItems)),
		  			  packageId:self.data.packageId,
		  			  calculate:encodeURI(JSON.stringify(self.data.totalPrice))
		            },
		            success(res) {
		                var order_id=res.data.data.order_id;
		                var pay_params=res.data.data.pay_params;
						var canpay=res.data.data.canpay;
						if(canpay == 1){
							wx.requestPayment({
								'timeStamp': pay_params.timeStamp,
								'nonceStr': pay_params.nonceStr,
								'package': pay_params.package,
								'signType': 'MD5',
								'paySign': pay_params.paySign,
								'success': function (resp) {
								  wx.hideLoading();
								  wx.showToast({
									title: '预约成功',
									icon: 'success',
									duration: 2000
								  });
								  setTimeout(() => {
									wx.navigateTo({
									  url: `/vp_pz/pages/physicalExam/orderIndex/index`
									});
								  }, 1500);
									   
								},
								'fail': function (res) {
									  wx.showToast({ title: '支付失败', icon: 'none' })
								}
							})
						}else{
							wx.showToast({
								title: '预约成功',
								icon: 'success',
								duration: 2000
							});
							setTimeout(() => {
								wx.navigateTo({
								  url: `/vp_pz/pages/physicalExam/orderIndex/index`
								});
							}, 1500);
						}
		            }
		    })
		  } catch (error) {
		    wx.showToast({ title: '提交失败', icon: 'none' })
		  }
		}
	})
  }
});